﻿@model Wiwi.ViewModels.ProfileView 
@{
 
    ViewBag.Title = "Profile";
    var HomeDir = System.Configuration.ConfigurationManager.AppSettings["HomeDirectory"].ToString(); 
}

<script type="text/javascript" >

    $(document).ready(function () {

        ///////////////////////////////////////////////////////////////////////////////////////////////////////
        var globalTags = [];
        var cnt1 = 0;
        // creates a public function within our private code.
        // tags can either be an array of strings OR
        // array of objects containing a 'tag' attribute
        window.setGlobalTags = function (tags /* array */) {
            globalTags = getTags(tags);
        };

        function getTags(tags) {
            //alert(tags.length);
            var tag, i, goodTags = [];
            for (i = 0; i < tags.length; i++) {
                tag = tags[i];
                if (typeof tags[i] == 'object') {
                    tag = tags[i].tag;
                }
                goodTags.push(tag.toLowerCase());
            }
            return goodTags;
        }

        $.fn.tagSuggest = function (options) {

            var defaults = {
                'matchClass': 'tagMatches',
                'tagContainer': 'span',
                'tagWrap': 'span',
                'sort': true,
                'tags': null,
                'url': null,
                'delay': 0,
                'separator': ' '
            };

            var i, tag, userTags = [], settings = $.extend({}, defaults, options);
            if (settings.tags) {
                userTags = getTags(settings.tags);
            } else {
                userTags = globalTags;

            }

            //alert(userTags.toString());
            return this.each(function () {
                var tagsElm = $(this);
                var elm = this;
                var matches, fromTab = false;
                var suggestionsShow = false;
                var workingTags = [];
                var currentTag = { "position": 0, tag: "" };
                var tagMatches = document.createElement(settings.tagContainer);

                function showSuggestionsDelayed(el, key) {
                    if (settings.delay) {
                        if (elm.timer) clearTimeout(elm.timer);
                        elm.timer = setTimeout(function () {
                            showSuggestions(el, key);
                        }, settings.delay);
                    } else {
                        showSuggestions(el, key);
                    }
                }

                //called 3 times
                function showSuggestions(el, key) {
                    workingTags = el.value.split(settings.separator);
                    //alert(workingTags.length);
                    matches = [];
                    var i, html = '', chosenTags = {}, tagSelected = false;

                    ////For sending to DB///////////////////
                    strs = $('#wiwi-create-want').val().split(settings.separator);
                    var lst = strs[strs.length - 1]
                    if (lst.length > 1 && lst.length < 6) {
                        if (lst.indexOf("#") > -1) {

                            var srchword = lst.substring(1, lst.length);
                            var http = new XMLHttpRequest();
                            var url = "@HomeDir/Home/KeyWords";
                            var params = "tag=" + srchword;
                            http.open("POST", url, true);
                            http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                            //                            http.setRequestHeader("Content-length", params.length);
                            //                            http.setRequestHeader("Connection", "close");
                            http.onreadystatechange = function () {//Call a function when the state changes.
                                if (http.readyState == 4 && http.status == 200) {
                                    globalTags = null;
                                    userTags = null;
                                    globalTags = [];
                                    userTags = [];
                                    tags = null;

                                    userTags = http.responseText;
                                    matches = http.responseText;
                                    globalTags = http.responseText;
                                    var ArrsStr = userTags.replace("[", "");
                                    ArrsStr = ArrsStr.replace("]", "");
                                    var Arrs = ArrsStr.split(",");
                                    //currentTag = { position: currentTags.length - 1, tag: '' };


                                    //matches = matches.sort();

                                    for (i = 0; i < Arrs.length; i++) {
                                        if (i == 0) { html += '<i>Tag Suggestions</i>'; }
                                        var ahr = Arrs[i].replace('"', '');
                                        ahr = ahr.replace('"', '');
                                        html += '<' + settings.tagWrap + ' class="_tag_suggestion">' + ahr + '</' + settings.tagWrap + '>';
                                    }

                                    tagMatches.html(html);
                                    suggestionsShow = !!(Arrs.length);
                                    //                                    for (i = 0; i < currentTags.length && i < workingTags.length; i++) {
                                    //                                        if (!tagSelected && currentTags[i].toLowerCase() != workingTags[i].toLowerCase()) {
                                    //                                            currentTag = { position: i, tag: workingTags[i].toLowerCase() };
                                    //                                            tagSelected = true;
                                    //                                        }
                                    //                                        chosenTags[currentTags[i].toLowerCase()] = true;
                                    //                                    }

                                    //                                    if (currentTag.tag) {
                                    //                                        for (i = 0; i < userTags.length; i++) {
                                    //                                            if (userTags[i].indexOf(currentTag.tag) === 0) {
                                    //                                                matches.push(userTags[i]);
                                    //                                            }
                                    //                                        }

                                    //                                        
                                    //                                    }
                                }
                            }
                            http.send(params);

                        }
                    }

                    // we're looking to complete the tag on currentTag.position (to start with)
                    //                    currentTag = { position: currentTags.length - 1, tag: '' };

                    //                    for (i = 0; i < currentTags.length && i < workingTags.length; i++) {
                    //                        if (!tagSelected &&
                    //                        currentTags[i].toLowerCase() != workingTags[i].toLowerCase()) {
                    //                            currentTag = { position: i, tag: workingTags[i].toLowerCase() };
                    //                            tagSelected = true;
                    //                        }
                    //                        // lookup for filtering out chosen tags
                    //                        chosenTags[currentTags[i].toLowerCase()] = true;
                    //                    }

                    //                    if (currentTag.tag) {
                    //                        // collect potential tags

                    //                        if (settings.url) {

                    //                        } else {
                    //                            //alert(userTags.length);
                    //                            for (i = 0; i < userTags.length; i++) {
                    //                                if (userTags[i].indexOf(currentTag.tag) === 0) {
                    //                                    matches.push(userTags[i]);
                    //                                }
                    //                            }
                    //                        }


                    //                        matches = $.grep(matches, function (v, i) {
                    //                            return !chosenTags[v.toLowerCase()];
                    //                        });

                    //                        if (settings.sort) {
                    //                            matches = matches.sort();
                    //                        }

                    //                        for (i = 0; i < matches.length; i++) {
                    //                            html += '<' + settings.tagWrap + ' class="_tag_suggestion">' + matches[i] + '</' + settings.tagWrap + '>';
                    //                        }

                    //                        tagMatches.html(html);
                    //                        suggestionsShow = !!(matches.length);
                    //                    } else {
                    //                        hideSuggestions();
                    //                    }
                }

                function AddKeywordTag(tag) {
                    for (var j = 0; j < $('#lstTag li').length; j++) {
                        var aref = $('#lstTag li a')[j];
                        if ($(aref).text() == tag) return false;
                    }
                    $('#lstTag').append('<li><a>' + tag + '</a></li>');
                    var val = $('#hidKeyWord').val();
                    $('#hidKeyWord').val(val + '?' + tag);
                    $('#lstTag li ').each(function () {
                        $(this).click(function () {
                            if (confirm('Are you sure to delete this keyword')) {
                                $(this).remove();
                                var val1 = '';
                                for (var j = 0; j < $('#lstTag li').length; j++) {
                                    var aref = $('#lstTag li a')[j];
                                    val1 += $(aref).text() + '?';
                                }
                                $('#hidKeyWord').val(val1);
                            }
                        });
                    });
                }
                function hideSuggestions() {
                    tagMatches.empty();
                    matches = [];
                    suggestionsShow = false;
                }

                function setSelection() {
                    var v = tagsElm.val();

                    if (v == tagsElm.attr('title') && tagsElm.is('.hint')) v = '';

                    currentTags = v.split(settings.separator);
                    hideSuggestions();
                }

                function chooseTag(tag) {
                    var i, index;
                    for (i = 0; i < currentTags.length; i++) {
                        if (currentTags[i].toLowerCase() != workingTags[i].toLowerCase()) {
                            index = i;
                            break;
                        }
                    }
                    //alert(tag);
                    AddKeywordTag(tag);
                    if (index == workingTags.length - 1) tag = tag + settings.separator;
                    workingTags[i] = tag;

                    tagsElm.val(workingTags.join(settings.separator));
                    tagsElm.blur().focus();
                    setSelection();
                }

                function handleKeys(ev) {
                    fromTab = false;
                    var type = ev.type;
                    var resetSelection = false;

                    if (ev.keyCode == 32) {
                        strs = $('#wiwi-create-want').val().split(settings.separator);
                        var lst = strs[strs.length - 1]
                        if (lst.indexOf("#") > -1) {
                            var srchword1 = lst.substring(1, lst.length);
                            srchword1 = srchword1.trim();
                            var http = new XMLHttpRequest();
                            var url = "@HomeDir/WantKeyword/AddkeyWord";
                            var params = "kw=" + srchword1;
                            http.open("POST", url, true);
                            http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                            http.setRequestHeader("Content-length", params.length);
                            http.setRequestHeader("Connection", "close");
                            http.onreadystatechange = function () {//Call a function when the state changes.
                                if (http.readyState == 4 && http.status == 200) {
                                    globalTags = null;
                                    userTags = null;
                                    globalTags = [];
                                    userTags = [];
                                    tags = null;
                                    var newval = $('#wiwi-create-want').val().replace("#", "");
                                    $('#wiwi-create-want').val(newval);
                                    AddKeywordTag(srchword1);
                                }
                            }
                            http.send(params);
                        }
                    }
                    switch (ev.keyCode) {
                        case 37: // ignore cases (arrow keys)
                        case 38:
                        case 39:
                        case 40:
                            {
                                hideSuggestions();
                                return true;
                            }
                        case 113: //F2
                            {
                                var isFF = false;
                                if (navigator.userAgent.toLowerCase().indexOf("firefox") > 0) {
                                    isFF = true;
                                }
                                var myArea = document.getElementById("wiwi-create-want");
                                var begin, selection, end;
                                if (isFF == true) {
                                    if (myArea.selectionStart != undefined) {
                                        begin = myArea.value.substr(0, myArea.selectionStart);
                                        selection = myArea.value.substr(myArea.selectionStart, myArea.selectionEnd - myArea.selectionStart);
                                        end = myArea.value.substr(myArea.selectionEnd);
                                    }
                                }
                                else {
                                    if (window.getSelection) {
                                        selection = window.getSelection();
                                    }
                                    else if (document.getSelection) {
                                        selection = document.getSelection();
                                    }
                                    else if (document.selection) {
                                        selection = document.selection.createRange().text;
                                    }
                                }
                                if (selection != "") {
                                    var http = new XMLHttpRequest();
                                    var url = "/WantKeyword/AddkeyWord";
                                    var params = "kw=" + selection;
                                    http.open("POST", url, true);

                                    //Send the proper header information along with the request
                                    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                                    http.setRequestHeader("Content-length", params.length);
                                    http.setRequestHeader("Connection", "close");

                                    http.onreadystatechange = function () {//Call a function when the state changes.
                                        if (http.readyState == 4 && http.status == 200) {
                                            globalTags = null;
                                            userTags = null;
                                            globalTags = [];
                                            userTags = [];
                                            tags = null;
                                            $('#wiwi-create-want').tagSuggest({
                                                url: 'Home/KeyWords/',
                                                delay: 0,
                                                sort: true
                                            });
                                            AddKeywordTag(selection);
                                        }
                                    }
                                    http.send(params);
                                }

                                return true;
                            }
                        case 224:
                        case 17:
                        case 16:
                        case 18:
                            {
                                return true;
                            }
                        case 8:
                            {
                                // delete - hide selections if we're empty
                                if (this.value == '') {
                                    hideSuggestions();
                                    setSelection();
                                    return true;
                                } else {

                                    type = 'keyup'; // allow drop through
                                    resetSelection = true;
                                    showSuggestionsDelayed(this);
                                }
                                break;
                            }

                        case 9: // return and tab
                        case 13:
                            {
                                //                                if (suggestionsShow) {
                                //                                    // complete
                                //                                    chooseTag(matches[0]);

                                //                                    fromTab = true;
                                //                                    return false;
                                //                                } else {
                                //                                    return true;
                                //                                }
                            }
                        case 27:
                            {
                                hideSuggestions();
                                setSelection();
                                return true;
                            }
                        case 32:
                            {
                                setSelection();
                                return true;
                            }
                    }

                    if (type == 'keyup') {

                        switch (ev.charCode) {
                            case 9:
                            case 13:
                                {
                                    return true;
                                }
                        }

                        if (resetSelection) {
                            setSelection();
                        }

                        showSuggestionsDelayed(this, ev.charCode);

                    }
                }

                tagsElm.after(tagMatches).keypress(handleKeys).keyup(handleKeys).blur(function () {
                    if (fromTab == true || suggestionsShow) { // tweak to support tab selection for Opera & IE
                        fromTab = false;
                        tagsElm.focus();
                    }
                });
                // replace with jQuery version
                tagMatches = $(tagMatches).click(function (ev) {
                    if (ev.target.nodeName == settings.tagWrap.toUpperCase() && $(ev.target).is('._tag_suggestion')) {
                        chooseTag(ev.target.innerHTML);
                    }
                }).addClass(settings.matchClass);

                // initialise
                setSelection();
            });
        };
        //        $('#tags-ajax').tagSuggest({
        //            url: '/Home/KeyWords',
        //            delay: 0,
        //            sort: true
        //        });
        $('#wiwi-create-want').tagSuggest({
            tags: [""]
        });
        $('#wiwi-create-form').submit(function () {
            //alert('Handler for .submit() called.');
            if ($('#lstTag li').length == 0) {
                alert('No keyword is selected. Please select keyword for the wiwi');
                return false;
            }

        });
    });
    

</script>
<!--
<div class="grid_8 box-shadow">
ds
</div>

<div class="grid_5 box-shadow">
ds
</div>
-->


<div class="grid_8">

    <form method="post" id="wiwi-create-form" action ="@HomeDir/WantKeyword/SaveWiwi/">

    <ul id="lstTag"></ul>

        <textarea cols="30"  rows="1" name="tags-ajax"  placeholder="What I want is" id="wiwi-create-want" class="fix"></textarea>
        <input type ="hidden" id="hidKeyWord" name="hidKeyWord" />
        <input type="submit" value="Create Want" id="submit-button" class="xWide moveRight" />

    </form>

</div>	

@* !Start WiWi search Wants *@
<div class="grid_5" id="wiwi-search">

	<form id="wiwi-profile-form-search">
		<input name="#" placeholder="Search Wants.. " id="main-search" class="fix" />  
		<input type="submit" value="Search" id="main-search-button" class="small" />
	</form>

</div>	


@* #end WiWi search Wants *@

<div class="grid_8 box-shadow margin-top">

    <h4 class="tabbed">Your Wants</h4>

    @if(Model.MyWants.Count == 0) {
        
        <div class="wiwi-profile-pitches-box">
            <p class="serif-it">You currently have no wants</p>
        </div>
        <hr />
    }

    @foreach (var wnt in Model.MyWants)
    { 
    <div class="wiwi-profile-pitches-box">
	
    	    <ul class="user-choice">
				<li><a href="/Want/CloseWant?Wuid=@wnt.UserWants.Want_Wanter_RelID.ToString()" class="grey-button button-s ">Close Wiwi</a></li>
        @* 2 new pitch's / 1 new pitch *@     
        @if (wnt.UserWants.NewPitches > 0) {
            string pitchs = "";
            if (wnt.UserWants.NewPitches > 1)
            {
                pitchs = "Pitch's";
            }
            else
            {
              pitchs = "Pitch";  
            }
            <li><a href ="/Want/UserPitch?Wuid=@wnt.UserWants.Want_Wanter_RelID.ToString()" class="blue-button button-s">@wnt.UserWants.NewPitches.ToString() new @pitchs</a></li>
        }
			</ul>
        
        <h4>Posted 2 days ago</h4>  @* !#! Needs date *@
        
        <p class="wiwi-content">@Html.ActionLink(wnt.UserWants.WantDesc, "WiwiDetails", "Home", new { wntID = wnt.UserWants.WantID, UsrID = wnt.UserWants.UserID }, null)</p>
     
        <p class='tagged'>Tagged ~
             @if (wnt.UserWants.Tags != "")
             {
                 string[] TagRows = wnt.UserWants.Tags.Split('$');
                 foreach (string tr in TagRows)
                 {
                     if (tr != "")
                     {
                         string[] Tagss = tr.Split('?');
                         if (Tagss[0].Trim() != "")
                         {
                            <a href='/Want/Pitch?Wuid=@Tagss[1].ToString()'>@Tagss[0]</a>
                         }
                     }
                 }
             }
             </p>

       
        @if (wnt.UserWants.WantUsers != "")
        {
    	    <div class="also-want grid_7">
          
    	@{
            string[] usrs = wnt.UserWants.WantUsers.Split('?');
            if (usrs.Length > 0)
            {
                <p class="move-left">Also <br />wanted by</p>
                
            @* <p class="move-right"> 12 others </p> // add if over x amount then show *@
                foreach (string us in usrs)
                {
                    if (us.Length > 16)
                    {
                    <a href ="/Home/UserPublicProfile?Uid=@us"><img height ="28" width="28" src='@Url.Action("ShowUserImage", "Home", new { Uid = @us })' /></a>
                    }
                }
            }

        }

         </div>
        <div class="clear"></div>
            
        }    
            
         @if (wnt.PitchesDetails.Count > 0)
         {
            <h3>Current dealings</h3>
             <div class="pitch-comments">
             @{
             foreach (var det in wnt.PitchesDetails)
             {
                <a href ="/Want/WantComm?Wid=@wnt.UserWants.Want_Wanter_RelID&SuppID=@det.UserSellerID"><img height ="48" width="48" src='@Url.Action("ShowUserImage", "Home", new { Uid = @det.UserSellerID })' /><span>@det.CommCount.ToString()</span></a>
    
             }
         }
                  </div>
         
         }
   
    	
  </div>
    
    <hr />
    }
    
    </div>

    @* ============ *@

    <div class="grid_5 box-shadow margin-top">
   
    <h4 class="tabbed">Your Pitches</h4> 

      @if (Model.SuppPitches.Count == 0)
      {
        
        <div class="wiwi-profile-pitches-box">
            <p class="serif-it">You have not yet pitched</p>

        </div>
        <hr />
      }

    @if (Model.SuppPitches != null)
    {
        foreach (var pt in Model.SuppPitches)
        {
        <div class="wiwi-profile-pitches-box"> 
               
               <p class="wiwi-content"><a href="#">@pt.NewPitches.WantDesc</a></p>
               @*<p class="wiwi-content">@Html.ActionLink(@pt.NewPitches.WantDesc, "WiwiDetails", "Home", new { wntID = @pt.NewPitches.WantID, UsrID = @pt.UserWants.UserID }, null)</p>       
           *@
                @foreach (var det in pt.PitchesDetails)
                {
                    if (det.IsClosed != true)
                    {

                        {
                            if (det.PitchStatus == true)
                            {
@*  <a href ="/Home/UserPublicProfile?Uid=@det.UserID"><img id="ImgPhoto" height ="48" width="48" src='@Url.Action("ShowUserImage", "Home", new { Uid = @det.UserID })' /></a>
*@                       

                            }
                            //   else
                            //   { 
                            //    <img id="ImgPhoto" height ="48px" width="48" src='@Url.Action("ShowUserImage", "Home", new { Uid = @det.UserID })' />
                            //    }
                        }
                        <ul class="user-choice">

                        @{
                        string strRet = "";
                        if (det.PitchStatus == true)
                        {
                         strRet = "Pitch Accepted";
                         <li class="green-button button-s xWide">@strRet</li>
                
                        }
                        else if (det.PitchStatus == false) { strRet = "Pitch Declined";
                         <li class="red-button button-s xWide">@strRet</li>
                        }

                        else if (det.PitchStatus == null) { strRet = "Pitch Pending";
                         <li class="grey-button button-s xWide">@strRet</li>
                        }
                        }
                        
                           
                        @{
                        string durat = "";
                        TimeSpan span = det.ExpiryDate.Value - DateTime.Now;
                        if (span.Minutes < 59 && span.Hours < 1 && span.Days < 1)
                        {
                            durat += "Expires in " + span.Minutes.ToString() + " Minutes";
                        }
                        if (span.Hours > 1 && span.Days < 1)
                        {
                            durat += "Expires in " + span.Hours.ToString() + " Hours";
                        }
                        if (span.Days > 1)
                        {
                            durat += "Expires in " + span.Days.ToString() + " Days";
                        }
                        }
                        @if(durat != "") {
                         <li class="yellow-button button-s xWide">@durat</li>
                         }
                        </ul> 

                                                                   if (strRet != "Declined")
                                                                   {
                                                                       if (det.CommCount != null)
                                                                       {
                                <div class="pitch-comments">
                                   <a href ="/Want/WantComm?Wid=@det.Want_Wanter_RelID&SuppID=@det.UserSellerID"><img height ="48" width="48" src='@Url.Action("ShowUserImage", "Home", new { Uid = @det.UserID })' /><span>@det.CommCount.ToString()</span></a>
    
                            @*    @Html.ActionLink(det.CommCount.ToString(), "WantComm", "Want", new { Wid = det.Want_Wanter_RelID, SuppID = det.UserSellerID }, null) *@
                                </div> 
                                                                       }
                                                                   }


                    }
                }
                @* Me to link 
                @{
                if (pt.NewPitches.MeTos > 0)
                {
                    <h5>@Html.ActionLink(pt.NewPitches.MeTos.ToString() + " Me2's recorded", "WiwiDetails", "Home", new { wntID = pt.NewPitches.WantID }, null)</h5>
                }
                }
                <h5>@Html.ActionLink("View and pitch", "WiwiDetails", "Home", new { wntID = @pt.NewPitches.WantID }, null)</h5>*@
            </div> 
        
        <hr class="mini" />
        }

    }
    </div>